import json
import re

from django.contrib.auth import login
from django.shortcuts import render
# from .models import OAuthQQUser

# Create your views here.
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall import settings
from django.http import JsonResponse


class QQLoginURLView(View):

    def get(self, request):
        # 1. 生成 QQLoginTool 实例对象
        # client_id=None,               appid
        # client_secret=None,           appsecret
        # redirect_uri=None,            用户同意登录之后，跳转的页面
        # state=None                    不知道什么意思，随便写。等出了问题再分析问题
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                   client_secret=settings.QQ_CLIENT_SECRET,
                   redirect_uri=settings.QQ_REDIRECT_URI,
                   state='xxxxx')
        # 2. 调用对象的方法生成跳转链接
        qq_login_url = qq.get_qq_url()
        # 3. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': qq_login_url})







class OauthQQView(View):
    '''
    获取code,通过code获取token.
    通过token获取openid
    如openid不存在就存入数据库并跳转到登陆成功页面
    如果openid存在直接跳转到登陆成功界面
    '''


    def get(self, request):

        code = request.GET.get('code')

         # 如果code不存在，则用户提供资料不全
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '资料提供不全'})

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx')

        token = qq.get_access_token(code)

        openid = qq.get_open_id(token)
        try:
            from apps.oauth.models import OAuthQQUser
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:

            # 加密oppenid
            # from apps.oauth.utils import generic_openid
            # openid = generic_openid(openid)


            return JsonResponse({'code': 0, 'access_token': openid})

        else:

            login(request, qquser.user)     # 系统方法记录会话状态  session
            requests = JsonResponse({'code': 0, 'errmsg': 'ok'})
            requests.set_cookie('username', qquser.user.username)   # 存储cookie
            return requests


    def post(self, request):
        # 获取mobile，password,sms_code,openid=access_token
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        mobile = json_dict['mobile']
        password = json_dict['password']
        sms_code = json_dict['sms_code']
        openid = json_dict['access_token']

        # openid的解密
        # from apps.oauth.utils import check_access_token
        # openid = check_access_token(openid)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg':'oppenid丢失'})

        # 如果参数不全，返回errmsg：参数不全
        if not all[mobile, password, sms_code, openid]:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 判断手机号是否正确

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code':400, 'errmsg': '请输入正确的手机号'})

        # 判断手机验证码是否正确，不正确返回响应




        # 通过手机号判断user是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:

            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)

        # 如果存在：先判断密码是否正确
        else:
        # 如果密码不正确返回：errmsg:密码错误
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号户密码错误'})
        # 如果密码正确的话user表中的user=user,openid=openid
        OAuthQQUser.objects.create(user=user, openid=openid)

        # cookie和session记录会话状态
        login(request,user)
        # 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.name)
        return response

        pass
